package com.app.twth.widget;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;

import androidx.appcompat.widget.AppCompatTextView;

import com.app.twth.R;


/**
 * @describe : 消息提示小红点
 */
public class RedPointTextView extends AppCompatTextView {
    private int mMinSize;
    private int mTopPadding;
    private int mLeftPadding;
    private static final int DEFAULT_TEXT_SIZE = 8; //dp
    private static final int DEFAULT_MIN_SIZE_DIP = 12; //最小尺寸
    private static final int DEFAULT_TB_PADDING_DIP = 1; //上下边距
    private static final int DEFAULT_LR_PADDING_DIP = 3; //左右边距
    private static final int DEFAULT_TEXT_COLOR = Color.WHITE;

    public RedPointTextView(Context context) {
        super(context);
        init();
    }

    public RedPointTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public RedPointTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mLeftPadding = dipToPixels(DEFAULT_LR_PADDING_DIP);
        mTopPadding = dipToPixels(DEFAULT_TB_PADDING_DIP);
        mMinSize = dipToPixels(DEFAULT_MIN_SIZE_DIP);

        setIncludeFontPadding(false);
        setGravity(Gravity.CENTER);
        setMinWidth(mMinSize);
        setMinHeight(mMinSize);
        setTextColor(DEFAULT_TEXT_COLOR);
        setTextSize(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_TEXT_SIZE);
        setBackgroundResource(R.drawable.bg_red_16);
        setVisibility(View.GONE);
    }

    private int dipToPixels(int dip) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, getResources().getDisplayMetrics());
    }

    public void setUnreadCount(int count) {
        if (count <= 0) {
            setVisibility(GONE);
        } else {
            setVisibility(VISIBLE);
            if (count < 10) {
                setPadding(0, 0, 0, 0);
            } else {
                setPadding(mLeftPadding, mTopPadding, mLeftPadding, mTopPadding);
            }
            if (count > 99) {
                setText("99+");
            } else {
                setText(String.valueOf(count));
            }
        }
    }
}
